package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"weibo-pub/cache"
	"weibo-pub/models"
	pkg2 "weibo-pub/pkg"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	login_key := "login_key" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, login_key).Int()
	if errcount >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.Password != pkg2.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, login_key)
		if errcount == 2 {
			cache.Rdb.Set(cache.Ctx, login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误3次，解封2小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}
func WeiBoList(c *gin.Context) {
	var weibos []models.WeiBo
	list_key := "list_key"
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Find(&weibos)
		cachedata, _ := json.Marshal(weibos)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &weibos)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": weibos,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var weibo models.WeiBo
	detail_key := "detail_key" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&weibo)
		cachedata, _ := json.Marshal(weibo)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &weibo)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": weibo,
	})
	return
}
